import { db, models } from '../../db';

const {
  config_item: ConfigItemModel,
  user: UserModel,
  user_item: UserItemModel,
  user_log_assets: UserLogAssetsModel,
  user_log_silver: UserLogSilverModel,
} = models;

export const goodsSell = async (user_id: string, data: Record<string, any>) => {
  const transaction = await db.transaction();

  return new Promise(async (resolve, reject) => {
    try {
      const { id, num } = data;

      if (num <= 0) {
        return;
      }

      const item = await UserItemModel.findOne({ where: { id, user_id } });

      if (!item) {
        return reject('物品不存在');
      }

      const { count, item_id } = item.dataValues;

      if (num > count) {
        return reject('数量不足');
      }

      const itemInfo = await ConfigItemModel.findOne({ where: { id: item_id } });
      const { sell } = itemInfo!.dataValues;
      const price = sell * num;

      await UserItemModel.update({ count: count - num }, { where: { id, user_id }, transaction });
      await UserLogAssetsModel.create(
        {
          user_id,
          type: 'use',
          assets_id: id,
          assets_type: 'item',
          reason_type: 'sell',
          reason: '出售道具',
        },
        {
          transaction,
        },
      );

      const userInfo = await UserModel.findOne({ where: { id: user_id } });
      const { silver } = userInfo!.dataValues;

      await UserModel.update({ silver: silver + price }, { where: { id: user_id }, transaction });

      await UserLogSilverModel.create(
        {
          user_id,
          type: 'get',
          count: price,
          reason_type: 'sell',
          reason: `出售道具-${id}`,
        },
        {
          transaction,
        },
      );

      await transaction.commit();
      resolve('ok');
    } catch (error) {
      console.log(error);
      await transaction.rollback();
    }
  });
};
